import { contextBridge, ipcRenderer } from "electron";

contextBridge.exposeInMainWorld("electronAPI", {
  send: (key: string, ...args: Array<any>) =>
    ipcRenderer.invoke("send", key, ...args),
  listen: (listenKey: string, ...args: Array<any>) => {
    let value = [];
    if (args.length > 2) {
      value = args.slice(1, args.length - 1);
    }
    let callback = args[args.length - 1];
    ipcRenderer.invoke("listen", listenKey, value);
    const eventName = "$event-" + listenKey;
    ipcRenderer.on(eventName, (event, ...args) => callback(...args));
  },
  closeListen: (key: string) => ipcRenderer.invoke("close-listen", key),
});
